//  Converts choice into html
//
//	Copyright (c) 2009, Krzysztof Langner
//	This code is released under MIT license

//-------------------------------------------------------------------------------------------------
function create_choice(input){
   	var choice = new ChoiceInteraction();
   	var	options = input.getElementsByTagName("simpleChoice");
   	
   	for(var i = 0; i < options.length; i++){
   		choice.addOption(parseInt(options[i].get("score")), options[i].innerHTML);
   	}

   	choice.reset();
   	return choice;
}

//--------------------------------------------------------------------------------------------------
var _choice_counter = 1;
var ChoiceInteraction = new Class({
	// constructor
    initialize: function(){
        this.options = new Array();
        this.maxScore = 0;
        this.result = 0;
        this.domNode = document.createElement("div");
        this.selectedIndex = -1;
        this.group_id = _choice_counter++;
    },

    // show answers
    reset: function(){
    	// reset score
    	this.selectedIndex = -1;
    	this.result = 0;
    	// Randomize options if necessery
    	// Create dom node
    	this.rebuildDOM(false);
    },
    
    // show answers
    showAnswers: function(){
    	this.rebuildDOM(true);
    },
    
    // get DOM
    getDOM: function(){
    	var root = this.domNode;
   		return root;
    },

    // ---------------------------------------------------------------------------------------------
    // Protected members
    // Add option to choice
    addOption: function(score, innerHtml){
    	var option = new Array();

    	option["score"] = score;
    	option["html"] = innerHtml;
    	this.options.push(option);

    	this.maxScore += score;
    },
    
    // change score
    optionClicked: function(index){
    	this.selectedIndex = index;
    	this.result = this.options[index]['score'];
    },
    
    // create DOM node
    rebuildDOM: function(showAnswers){
    	var root = this.domNode;
   		var option, button, text;
   		var self = this;

    	// remove old nodes
    	while( root.hasChildNodes() ){
    		root.removeChild(root.firstChild);
    	}
   		
    	// Add options
   		this.options.each(function(item, index){
   	   		option = document.createElement("div");
   	   		points = document.createTextNode('[' +  item['score'] + ']' );
   	   		button = new Element( 'input', {
   	   			'type': "radio", 
   	   			'name' : "choice_" + self.group_id,
   				'events': {
   		   	        'click': function(){self.optionClicked(index);}
   	   			}
   	   		} );
   	   		if(index == self.selectedIndex)
   	   			button.checked = 'true';
   	   		text = document.createTextNode( item['html'] );
   	   	
   	   		if(showAnswers)
   	   			option.appendChild(points);
   	   		option.appendChild(button);
   	   		option.appendChild(text);
   	   		root.appendChild(option);
   		});
    	
    }
    
});

